<template>
  <div class="system-settings">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>系统设置</h2>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 基本设置 -->
        <el-tab-pane label="基本设置" name="basic">
          <el-form
            ref="basicFormRef"
            :model="basicForm"
            :rules="basicRules"
            label-width="120px"
            class="settings-form"
          >
            <el-form-item label="网站名称" prop="siteName">
              <el-input v-model="basicForm.siteName" />
            </el-form-item>
            <el-form-item label="网站描述" prop="siteDescription">
              <el-input
                v-model="basicForm.siteDescription"
                type="textarea"
                :rows="3"
              />
            </el-form-item>
            <el-form-item label="网站Logo">
              <el-upload
                class="logo-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeLogoUpload"
              >
                <img v-if="basicForm.logo" :src="basicForm.logo" class="logo" />
                <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="ICP备案号" prop="icpNumber">
              <el-input v-model="basicForm.icpNumber" />
            </el-form-item>
            <el-form-item label="版权信息" prop="copyright">
              <el-input v-model="basicForm.copyright" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleBasicSave">
                保存设置
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 安全设置 -->
        <el-tab-pane label="安全设置" name="security">
          <el-form
            ref="securityFormRef"
            :model="securityForm"
            label-width="200px"
            class="settings-form"
          >
            <el-form-item label="登录验证码">
              <el-switch v-model="securityForm.loginCaptcha" />
              <span class="form-tip">开启后，登录时需要输入验证码</span>
            </el-form-item>
            <el-form-item label="注册验证码">
              <el-switch v-model="securityForm.registerCaptcha" />
              <span class="form-tip">开启后，注册时需要输入验证码</span>
            </el-form-item>
            <el-form-item label="密码最小长度" prop="passwordMinLength">
              <el-input-number
                v-model="securityForm.passwordMinLength"
                :min="6"
                :max="20"
              />
            </el-form-item>
            <el-form-item label="密码复杂度要求">
              <el-checkbox-group v-model="securityForm.passwordRules">
                <el-checkbox label="uppercase">必须包含大写字母</el-checkbox>
                <el-checkbox label="lowercase">必须包含小写字母</el-checkbox>
                <el-checkbox label="number">必须包含数字</el-checkbox>
                <el-checkbox label="special">必须包含特殊字符</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="登录失败限制" prop="loginAttempts">
              <el-input-number
                v-model="securityForm.loginAttempts"
                :min="3"
                :max="10"
              />
              <span class="form-tip">次后锁定账号</span>
            </el-form-item>
            <el-form-item label="账号锁定时间" prop="lockTime">
              <el-input-number
                v-model="securityForm.lockTime"
                :min="5"
                :max="60"
              />
              <span class="form-tip">分钟</span>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSecuritySave">
                保存设置
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 邮件设置 -->
        <el-tab-pane label="邮件设置" name="email">
          <el-form
            ref="emailFormRef"
            :model="emailForm"
            :rules="emailRules"
            label-width="120px"
            class="settings-form"
          >
            <el-form-item label="SMTP服务器" prop="smtpHost">
              <el-input v-model="emailForm.smtpHost" />
            </el-form-item>
            <el-form-item label="SMTP端口" prop="smtpPort">
              <el-input v-model="emailForm.smtpPort" />
            </el-form-item>
            <el-form-item label="加密方式" prop="smtpEncryption">
              <el-select v-model="emailForm.smtpEncryption">
                <el-option label="无" value="none" />
                <el-option label="SSL" value="ssl" />
                <el-option label="TLS" value="tls" />
              </el-select>
            </el-form-item>
            <el-form-item label="发件人邮箱" prop="smtpUsername">
              <el-input v-model="emailForm.smtpUsername" />
            </el-form-item>
            <el-form-item label="邮箱密码" prop="smtpPassword">
              <el-input
                v-model="emailForm.smtpPassword"
                type="password"
                show-password
              />
            </el-form-item>
            <el-form-item label="发件人名称" prop="smtpFromName">
              <el-input v-model="emailForm.smtpFromName" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleEmailSave">
                保存设置
              </el-button>
              <el-button @click="handleTestEmail">
                发送测试邮件
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const activeTab = ref('basic')

// 基本设置
const basicFormRef = ref(null)
const basicForm = reactive({
  siteName: '在线教育平台',
  siteDescription: '提供优质的在线教育服务',
  logo: '',
  icpNumber: '',
  copyright: '© 2024 在线教育平台 版权所有'
})

const basicRules = {
  siteName: [
    { required: true, message: '请输入网站名称', trigger: 'blur' }
  ],
  siteDescription: [
    { required: true, message: '请输入网站描述', trigger: 'blur' }
  ]
}

// 安全设置
const securityFormRef = ref(null)
const securityForm = reactive({
  loginCaptcha: true,
  registerCaptcha: true,
  passwordMinLength: 8,
  passwordRules: ['uppercase', 'number'],
  loginAttempts: 5,
  lockTime: 30
})

// 邮件设置
const emailFormRef = ref(null)
const emailForm = reactive({
  smtpHost: '',
  smtpPort: '465',
  smtpEncryption: 'ssl',
  smtpUsername: '',
  smtpPassword: '',
  smtpFromName: '在线教育平台'
})

const emailRules = {
  smtpHost: [
    { required: true, message: '请输入SMTP服务器地址', trigger: 'blur' }
  ],
  smtpPort: [
    { required: true, message: '请输入SMTP端口', trigger: 'blur' }
  ],
  smtpUsername: [
    { required: true, message: '请输入发件人邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  smtpPassword: [
    { required: true, message: '请输入邮箱密码', trigger: 'blur' }
  ],
  smtpFromName: [
    { required: true, message: '请输入发件人名称', trigger: 'blur' }
  ]
}

// Logo上传
const beforeLogoUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传Logo只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传Logo图片大小不能超过 2MB!')
    return false
  }

  // 模拟上传
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    basicForm.logo = reader.result
  }
  return false
}

// 保存基本设置
const handleBasicSave = async () => {
  if (!basicFormRef.value) return
  
  try {
    await basicFormRef.value.validate()
    // TODO: 调用API保存基本设置
    localStorage.setItem('adminBasicSettings', JSON.stringify(basicForm)); // 保存到 localStorage (管理员专用)
    ElMessage.success('基本设置保存成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 保存安全设置
const handleSecuritySave = async () => {
  if (!securityFormRef.value) return
  
  try {
    await securityFormRef.value.validate()
    // TODO: 调用API保存安全设置
    localStorage.setItem('adminSystemSecuritySettings', JSON.stringify(securityForm)); // 保存到 localStorage (管理员专用)
    ElMessage.success('安全设置保存成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 保存邮件设置
const handleEmailSave = async () => {
  if (!emailFormRef.value) return

  try {
    await emailFormRef.value.validate()
    // TODO: 调用API保存邮件设置
    localStorage.setItem('adminEmailSettings', JSON.stringify(emailForm)); // 保存到 localStorage (管理员专用)
    ElMessage.success('邮件设置保存成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 发送测试邮件
const handleTestEmail = () => {
  // TODO: 调用API发送测试邮件
  ElMessage.info('发送测试邮件功能开发中')
}

// 加载设置
const loadSettings = () => {
  const savedBasicSettings = localStorage.getItem('adminBasicSettings'); // 从 localStorage (管理员专用) 读取
  if (savedBasicSettings) {
    try {
      Object.assign(basicForm, JSON.parse(savedBasicSettings));
    } catch (e) {
      console.error('Failed to load admin basic settings from localStorage:', e);
    }
  }

  const savedSecuritySettings = localStorage.getItem('adminSystemSecuritySettings'); // 从 localStorage (管理员专用) 读取
  if (savedSecuritySettings) {
    try {
      // Ensure passwordRules is an array if it's null or undefined in localStorage
      const loadedSecuritySettings = JSON.parse(savedSecuritySettings);
      if (!Array.isArray(loadedSecuritySettings.passwordRules)) {
        loadedSecuritySettings.passwordRules = [];
      }
      Object.assign(securityForm, loadedSecuritySettings);
    } catch (e) {
      console.error('Failed to load admin system security settings from localStorage:', e);
    }
  }

  const savedEmailSettings = localStorage.getItem('adminEmailSettings'); // 从 localStorage (管理员专用) 读取
  if (savedEmailSettings) {
    try {
      Object.assign(emailForm, JSON.parse(savedEmailSettings));
    } catch (e) {
      console.error('Failed to load admin email settings from localStorage:', e);
    }
  }
};

onMounted(() => {
  loadSettings(); // 在组件挂载时加载设置
})
</script>

<style scoped>
.system-settings {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
}

.settings-form {
  max-width: 800px;
  margin: 20px auto;
}

.logo-uploader {
  text-align: center;
}

.logo-uploader .logo {
  width: 200px;
  height: 60px;
  object-fit: contain;
}

.logo-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.logo-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 60px;
  text-align: center;
  line-height: 60px;
}

.form-tip {
  margin-left: 10px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}
</style> 